﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows.Input;
using MediaPlayer.Model;

namespace MediaPlayer.ViewModel
{
    class PlayListViewModel : ViewModelBase
    {
        #region Fields

        private ObservableCollection<Song> songs;
        private ICollectionView collectionViewSongs;

        #endregion

        #region Properties

        public ICollectionView CollectionViewSongs
        {
            get
            {
                return this.collectionViewSongs;
            }
        }

        public string Name
        {
            get
            {
                return this.PlayList.Name;
            }
            set
            {
                if (value != this.PlayList.Name)
                {
                    this.PlayList.Name = value;
                    this.OnPropertyChanged("Name");
                }
            }
        }

        public ObservableCollection<Song> Songs
        {
            get
            {
                return this.songs;
            }
        }

        public PlayList PlayList
        {
            get;
            private set;
        }

        public Song SelectedSong
        {
            get
            {
                return this.collectionViewSongs.CurrentItem as Song;
            }
        }

        #endregion

        #region Method
        public void DoQuery(string search)
        {
            IEnumerable<Song> listQuery = 
                    (from song in this.PlayList.SongList
                     where (song.Name.ToLower().Contains(search) ||
                     song.Album.ToLower().Contains(search) ||
                     song.AlbumArtist[0].ToLower().Contains(search) ||
                     song.FileName.ToLower().Contains(search))
                     select song);

            this.songs.Clear();
            foreach (Song song in listQuery)
            {
                this.songs.Add(song);
            }
        }

        public void ResetView()
        {
            this.songs.Clear();
            foreach (Song song in this.PlayList.SongList)
            {
                this.songs.Add(song);
            }
        }
        #endregion

        public PlayListViewModel(PlayList playList)
        {
            this.PlayList = playList;
            this.songs = new ObservableCollection<Song>(this.PlayList.SongList);
            this.collectionViewSongs = new ListCollectionView(this.songs);
            if (this.collectionViewSongs == null)
                throw new NullReferenceException("collectionViewSongs");
        }
    }
}
